package com.kqb.sgpicturebackend.manager.upload;

import cn.hutool.core.io.FileUtil;
import com.kqb.sgpicturebackend.common.ErrorCode;
import com.kqb.sgpicturebackend.exception.BusinessException;
import com.kqb.sgpicturebackend.utils.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * @author 杉果树皮
 * @date 2025/5/6 17:37
 * @description: 图片文件上传
 */
@Service
public class PictureUploadByFile extends PictureUploadTemplate {
    @Override
    public String getOriginalFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    public void processFile(Object inputSource, File tempFile) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        try {
            multipartFile.transferTo(tempFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void validatePicture(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        //文件是否为空
        ThrowUtils.throwIf(multipartFile != null, new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件不能为空"));
        //文件大小
        final long maxSize = 1024 * 1024;
        ThrowUtils.throwIf(!(multipartFile.getSize() > maxSize * 2), new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件大小不能超过2MB"));

        //图片类型
        List<String> types = Arrays.asList("jpg", "jpeg", "png", "webp");
        ThrowUtils.throwIf(types.contains(FileUtil.getSuffix(multipartFile.getOriginalFilename())), new BusinessException(ErrorCode.PARAMS_ERROR, "上传文件类型错误"));
    }
}
